package com.zyw.boot.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MachineFileTranslator {

    // 科大讯飞翻译API相关参数
    private static String requestUrl = "https://itrans.xf-yun.com/v1/its";
    private static final String APP_ID = "appid";
    private static final String API_KEY = "api_key";// 替换为你的API_KEY
    private static final String API_SECRET = "api_secret"; // 替换为你的APIKey
    private static final String RES_ID = "its_cn_en_word"; // 术语资源唯一标识，如不需术语可以不用传递此参数

    //private static final String INPUT_FOLDER = "C:\\Users\\yiwen_zheng\\Desktop\\test"; // 输入文件夹路径
    //private static final String OUTPUT_FOLDER = "C:\\Users\\yiwen_zheng\\Desktop\\test2";

    // 输入和输出文件夹路径
    private static final String INPUT_FOLDER = "D:\\SoftWare\\Command Modern Operations\\DB\\Descriptions\\submarine"; // 输入文件夹路径
    private static final String OUTPUT_FOLDER = "D:\\SoftWare\\Command Modern Operations\\DB\\DescriptionsChinese\\DB3000"; // 输出文件夹路径

    private static String parseTranslationResult(String response) {
        try {
            JSONObject jsonResponse = JSON.parseObject(response);
            JSONObject payload = jsonResponse.getJSONObject("payload");
            JSONObject result = payload.getJSONObject("result");
            String textBase64 = result.getString("text");
            String translatedText = new String(Base64.getDecoder().decode(textBase64), StandardCharsets.UTF_8);
            JSONObject trans =  JSONObject.parseObject(translatedText);
            String resultText = trans.getJSONObject("trans_result").getString("dst");
            return resultText;
        } catch (Exception e) {
            e.printStackTrace();
            return "翻译失败";
        }
    }

    // 线程池大小
    private static final int THREAD_POOL_SIZE = 10;

    public static void main(String[] args) {
        // 创建输出文件夹（如果不存在）
        createFolder(OUTPUT_FOLDER);

        // 获取输入文件夹中的所有文件
        File folder = new File(INPUT_FOLDER);
        File[] files = folder.listFiles(File::isFile);

        if (files == null || files.length == 0) {
            System.out.println("输入文件夹中没有文件！");
            return;
        }

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        // 使用线程池处理每个文件
        List<Future<?>> futures = new ArrayList<>();
        for (File file : files) {
            futures.add(executor.submit(() -> {
                try {
                    processFile(file);
                } catch (Exception e) {
                    System.err.println("处理文件 " + file.getName() + " 时出错: " + e.getMessage());
                    e.printStackTrace();
                }
            }));
        }

        // 等待所有任务完成
        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        // 关闭线程池
        executor.shutdown();

        System.out.println("所有文件翻译完成！");
    }

    // 处理单个文件
    private static void processFile(File file) throws Exception {
        // 读取文件内容
        List<String> lines = readLinesFromFile(file);
        // 翻译内容
        List<String> translatedLines = translateLines(lines);

        // 保存翻译后的内容到输出文件夹
        saveLinesToFile(translatedLines, OUTPUT_FOLDER, file.getName());

        System.out.println("文件 " + file.getName() + " 翻译完成！");
    }

    // 创建文件夹
    private static void createFolder(String folderPath) {
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    // 逐行读取文件内容
    private static List<String> readLinesFromFile(File file) throws IOException {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }

    // 翻译所有行
    private static List<String> translateLines(List<String> lines) throws Exception {
        List<String> translatedLines = new ArrayList<>();
        for (String line : lines) {
            // 翻译每一行
            String translatedLine = translate(line);
            translatedLines.add(translatedLine);
        }
        return translatedLines;
    }

    // 调用科大讯飞翻译API
    private static String translate(String text) throws Exception {
        if (text == null || text.isEmpty()) {
            return ""; // 如果文本为空，直接返回空字符串
        }

        // 构建请求URL
        String requestUrlWithAuth = buildRequestUrl();

        URL realUrl = new URL(requestUrlWithAuth);
        HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-type", "application/json");

        // 构建请求参数
        String params = buildParam(text);
        OutputStream out = httpURLConnection.getOutputStream();
        out.write(params.getBytes(StandardCharsets.UTF_8));
        out.flush();

        // 获取响应
        int responseCode = httpURLConnection.getResponseCode();
        InputStream is;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            is = httpURLConnection.getInputStream();
        } else {
            is = httpURLConnection.getErrorStream();
        }
        String response = readAllBytes(is);

        // 解析翻译结果
        return parseTranslationResult(response);
    }

    // 构建请求URL，包含鉴权
    private static String buildRequestUrl() {
        try {
            URL url = new URL(requestUrl);
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = format.format(new Date());
            String host = url.getHost();

            StringBuilder builder = new StringBuilder("host: ").append(host).append("\n")
                    .append("date: ").append(date).append("\n")
                    .append("POST ").append(url.getPath()).append(" HTTP/1.1");
            Mac mac = Mac.getInstance("hmacsha256");
            SecretKeySpec spec = new SecretKeySpec(API_SECRET.getBytes(StandardCharsets.UTF_8), "hmac-sha256");
            mac.init(spec);
            byte[] hexDigits = mac.doFinal(builder.toString().getBytes(StandardCharsets.UTF_8));
            String sha = Base64.getEncoder().encodeToString(hexDigits);

            String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", API_KEY, "hmac-sha256", "host date request-line", sha);
            String authBase = Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8));

            return String.format("%s?authorization=%s&host=%s&date=%s", requestUrl, URLEncoder.encode(authBase), URLEncoder.encode(host), URLEncoder.encode(date));
        } catch (Exception e) {
            throw new RuntimeException("构建请求URL时出错: " + e.getMessage());
        }
    }

    // 构建请求参数
    private static String buildParam(String text) {
        return "{"
                + "  \"header\": {"
                + "    \"app_id\": \"" + APP_ID + "\","
                + "    \"status\": 3,"
                + "    \"res_id\": \"" + RES_ID + "\""
                + "  },"
                + "  \"parameter\": {"
                + "    \"its\": {"
                + "      \"from\": \"en\","
                + "      \"to\": \"cn\","
                + "      \"result\": {}"
                + "    }"
                + "  },"
                + "  \"payload\": {"
                + "    \"input_data\": {"
                + "      \"encoding\": \"utf8\","
                + "      \"status\": 3,"
                + "      \"text\": \"" + Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8)) + "\""
                + "    }"
                + "  }"
                + "}";
    }

    // 读取流数据
    private static String readAllBytes(InputStream is) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            return content.toString();
        }
    }



    // 逐行保存翻译后的内容到文件
    private static void saveLinesToFile(List<String> lines, String folder, String fileName) throws IOException {
        File outputFile = new File(folder, fileName);
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        }
    }


}